package com.cl.ks.service;

import com.alibaba.fastjson.JSONObject;
import com.cl.ks.entity.KsFilter;
import com.cl.ks.repository.KsFilterRepository;
import com.cl.ks.utils.DbUtil;
import com.cl.ks.utils.FieldUtil;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.cl.ks.constant.QTableConstant.qKsFilter;

/**
 * @author chenyitao
 * @date 2021/7/5
 */
@Service
@Slf4j
public class AutoFilterService {
    private final FilterAsyncService filterAsyncService;
//    private final DataSource msgDataSource;

    private final JPAQueryFactory queryFactory;

    private final KsFilterRepository ksFilterRepository;

    private final DbUtil dbUtil;

    @Data
    public static class MessageItem {
        private String taskName;

        private Integer newMatch;

        private Integer newNotMatch;

        private String downloadId;
    }

    public AutoFilterService(FilterAsyncService filterAsyncService,
                              JPAQueryFactory jpaQueryFactory, KsFilterRepository ksFilterRepository, DbUtil dbUtil) {
        this.queryFactory = jpaQueryFactory;
        this.filterAsyncService = filterAsyncService;
        this.ksFilterRepository = ksFilterRepository;
        this.dbUtil = dbUtil;
    }

    public void autoUpdate() {
        BooleanExpression booleanExpression = qKsFilter.status.ne(0).and(qKsFilter.isTask.eq(true));
        Long filterCount = queryFactory.select(qKsFilter.count()).from(qKsFilter).where(booleanExpression).fetchOne();
        int current = 0;
        int batchSize = 1;
        while (current < filterCount) {
            List<KsFilter> filterList = queryFactory.selectFrom(qKsFilter).where(booleanExpression).offset(current).limit(batchSize).fetch();
            for (KsFilter ksFilter : filterList) {
                log.info("开始执行抗诉任务 {}", ksFilter.getFilterName());
                try {
                    FilterService.FilterBundle filterBundle = JSONObject.parseObject(
                            ksFilter.getFilterBundle(), FilterService.FilterBundle.class);
                    filterAsyncService.filterSync(ksFilter.getId(), filterBundle);
                } catch (Exception e) {
                    log.error("抗诉任务 {} 出现异常 {}", ksFilter.getFilterName(), e.getMessage());
                }
            }
            current += batchSize;
        }
    }


    public void initLastPosition() {
        List<KsFilter> filterRecords = queryFactory.selectFrom(qKsFilter).fetch();
        for (KsFilter record : filterRecords) {
            FilterService.FilterBundle filterBundle = JSONObject.parseObject(
                    record.getFilterBundle(), FilterService.FilterBundle.class);
            try {
                for (FilterService.FilterParam filterParam : filterBundle.getFilterParams()) {
                    if (filterParam.getLastPosition() == null) {
                        int count = (int) dbUtil.fetchSQL(null, "SELECT COUNT(*) as count FROM " + filterParam.getTableName()).get(0).get("count");
                        filterParam.setLastPosition(count);
                    }
                }
                record.setFilterBundle(JSONObject.toJSONString(filterBundle));
                ksFilterRepository.save(record);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }
}
